package hu.test.atacama;

import hu.test.atacama.Common.mButtonClickListener;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.StrictMode;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
		mButtonClickListener {

	private pageAdapter mPageAdapter;
	private ViewPager mPager;

	IntentFilter commServIntentFilter, commServErrorIntentFilter, getLocationIntentFilter,
					bluetoothConnectedIntentFilter, bluetoothDisconnectedIntentFilter;
	final Intent commServiceIntent = new Intent();
	CommServiceReceiver commServiceReceiver = new CommServiceReceiver();

	LocationManager lm;
	Common common;
	Vibrator vibrator;
	long vibrationLength;

	GetLocation gpsService;

	boolean gpsServiceBound = false;
	boolean isGPSEnabled = false;
	boolean isNetworkEnabled = false;
	private static boolean showParkingMap = false;

	FragmentMain fragmentMain = new FragmentMain();
	FragmentSummary fragmentSummary = new FragmentSummary();
	FragmentParking fragmentParking = new FragmentParking();

	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	BluetoothDevice arduinoBluetooth;
	BluetoothSocket mBluetoothSocket;
	boolean arduinoBluetoothConnected = false;
	
	String TAG = "MainActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);

		FragmentTransaction fragmentTransaction = getSupportFragmentManager()
				.beginTransaction();
		fragmentTransaction.add(R.id.id_fragment_main, fragmentMain);
		fragmentTransaction.add(R.id.id_fragment_summary, fragmentSummary);
		fragmentTransaction.add(R.id.id_fragment_parking, fragmentParking);
		fragmentTransaction.commit();

		setContentView(R.layout.activity_main);
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}

		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		mPageAdapter = new pageAdapter(getSupportFragmentManager());
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mPageAdapter);

		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrationLength = Long
				.parseLong(getString(R.string.sys_option_vibration_length));

		common = Common.getInstance(this);

		commServiceIntent.setClass(getApplicationContext(), CommService.class);
		commServIntentFilter = new IntentFilter(CommService.COMMSERVICE_DONE);
		commServErrorIntentFilter = new IntentFilter(CommService.COMMSERVICE_ERROR);
		
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		getLocationIntentFilter = new IntentFilter(GetLocation.LOCATION_CHANGED);
		// locInfoServiceIntent.setClass(this, LocInfoService.class);

		isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		if (!isGPSEnabled) {
			gpsDisabledAlert();
		}
		
		
		if (mBluetoothAdapter != null) {
			if (!mBluetoothAdapter.isEnabled()) {
			    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			    startActivityForResult(enableBtIntent, Common.REQUEST_ENABLE_BT);
			}
			bluetoothConnectedIntentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
			bluetoothDisconnectedIntentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
//			bluetoothConnectedIntentFilter = new IntentFilter(mBluetoothAdapter.getRemoteDevice(Common.ARDUINO_BLUETOOTH_MAC).ACTION_ACL_CONNECTED);						
		}	
	}
	
	public static class pageAdapter extends FragmentStatePagerAdapter {

		public pageAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
			// return super.getItemPosition(object);
		}

		@Override
		public Fragment getItem(int arg0) {
			switch (arg0) {
			case 0:
				return showParkingMap ? new FragmentParking()
						: new FragmentMain();
			case 1:
				return new FragmentSummary();
			case 2:
				return new FragmentParking();
			default:
				return null;
			}
		}

		@Override
		public int getCount() {
			return showParkingMap ? 1 : Common.NUMBER_OF_PAGES;
		}

	}

	@Override
	public void onBackPressed() {
		if (mPager.getCurrentItem() == 0) {
			if (showParkingMap) {
				showParkingMap = false;
				mPageAdapter.notifyDataSetChanged();
				mPager.setCurrentItem(0);
				refreshSummaryText();
			} else {
				super.onBackPressed();
			}
		} else {
			mPager.setCurrentItem(mPager.getCurrentItem() - 1);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent getLocationIntent = new Intent(this, GetLocation.class);
		bindService(getLocationIntent, gpsConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {		
		unregisterReceiver(bluetoothDisconnectReceiver);
		unregisterReceiver(bluetoothConnectReceiver);
		unregisterReceiver(getLocationReceiver);		
		unregisterReceiver(commServiceDone);
		unregisterReceiver(commServiceReceiver);
		unregisterReceiver(commServiceError);
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		registerReceiver(commServiceDone, commServIntentFilter);
		registerReceiver(commServiceReceiver, commServIntentFilter);
		registerReceiver(commServiceError, commServErrorIntentFilter);
		registerReceiver(getLocationReceiver, getLocationIntentFilter);
		registerReceiver(bluetoothConnectReceiver, bluetoothConnectedIntentFilter);
		registerReceiver(bluetoothDisconnectReceiver, bluetoothDisconnectedIntentFilter);
		
		bluetoothConnect(Common.ARDUINO_BLUETOOTH_MAC);
	}

	@Override
	protected void onStop() {
		if (gpsServiceBound) {
			unbindService(gpsConnection);
			gpsServiceBound = false;
		}		
		bluetoothCloseConnection();
		super.onStop();
	}

	private ServiceConnection gpsConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			gpsServiceBound = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			gpsService = ((GetLocation.LocalBinder) service).getService();
			gpsServiceBound = true;
			refreshSummaryText();
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			switch (item.getItemId()) {
			case R.id.menu_settings:
				Intent settingsIntent = new Intent(MainActivity.this,
						AtacamaSettings.class);
				startActivity(settingsIntent);
				return true;
			case R.id.menu_sync_cars:
				getCarList();
				return true;
			case R.id.menu_sync_gps:
				uploadSavedLocations();
				return true;
			case R.id.menu_start_service:
				if (!isLocInfoServiceRunning()) {
					startLocinfoService();
				} else {
					common.displayToast(getString(R.string.message_service_running));
				}
				return true;
			case R.id.menu_stop_service:
				PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
				PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(
						PowerManager.PARTIAL_WAKE_LOCK, "");
				if (mWakeLock.isHeld()) {
					mWakeLock.release();
				}

				Intent mAlarm = new Intent(this, AlarmReceiver.class);
				PendingIntent mPendingIntent = PendingIntent.getBroadcast(this,
						0, mAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
				AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
				alarms.cancel(mPendingIntent);
				common.displayToast(getString(R.string.message_service_stopping));

				/*
				if (isLocInfoServiceRunning()) {
					Intent locInfoIntent = new Intent(this,
							LocInfoService.class);
					stopService(locInfoIntent);
				}
				*/				
				return true;
			case R.id.menu_exit:
				Toast.makeText(getApplicationContext(), R.string.message_exit,
						Toast.LENGTH_SHORT).show();
				finish();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		} catch (Exception ex) {
			Toast.makeText(getApplicationContext(),
					"MainActivity / onOptionsItemSelected: " + ex.toString(),
					Toast.LENGTH_LONG).show();
			return super.onOptionsItemSelected(item);
		}
	}

	private void startLocinfoService() {
		if (!isLocInfoServiceRunning()) {
			vibrator.vibrate(150);
			Intent mAlarm = new Intent(this, AlarmReceiver.class);
			PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0,
					mAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
			// alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
			alarms.setRepeating(AlarmManager.RTC_WAKEUP,
					System.currentTimeMillis(), common.getGPSRefreshMinTime(),
					mPendingIntent);
		}
	}

	private void gpsDisabledAlert() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.message_gpsNotEnabled)
				.setCancelable(false)
				.setPositiveButton(R.string.message_enableGPS,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								showGpsOptions();
								isGPSEnabled = lm
										.isProviderEnabled(LocationManager.GPS_PROVIDER);
							}
						});
		builder.setNegativeButton(R.string.message_leaveGPSDisabled,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void showGpsOptions() {
		Intent gpsOptionsIntent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(gpsOptionsIntent);
	}

	private boolean isLocInfoServiceRunning() {
		return isServiceRunning(LocInfoService.class);
	}

	private boolean isServiceRunning(
			@SuppressWarnings("rawtypes") Class className) {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (className.getName().equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	private BroadcastReceiver getLocationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			refreshSummaryText();
		}
	};

	private final BroadcastReceiver bluetoothConnectReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
        	BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        	if (device.getAddress().equals(Common.ARDUINO_BLUETOOTH_MAC))
            {
                Log.d(TAG, getString(R.string.message_bluetooth_connected));
                arduinoBluetoothConnected = true;
            }
        }
    };
    
    private final BroadcastReceiver bluetoothDisconnectReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
        	BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        	if (device.getAddress().equals(Common.ARDUINO_BLUETOOTH_MAC))
            {
        		Log.d(TAG, getString(R.string.message_bluetooth_disconnected));
                arduinoBluetoothConnected = false;
            }
        }
    };
	
	private void refreshSummaryText() {
		StringBuilder builder = new StringBuilder();
		builder.append(getString(R.string.text_main_summary)
				+ System.getProperty("line.separator")
				+ System.getProperty("line.separator"));
		builder.append("Controlled car: " + common.getCurrentCarName()
				+ System.getProperty("line.separator"));
		builder.append("Device type: " + common.getDeviceType()
				+ System.getProperty("line.separator"));
		builder.append("Operation mode: " + common.getOperationMode()
				+ System.getProperty("line.separator"));
		builder.append("Sender ID: " + common.getSenderID()
				+ System.getProperty("line.separator"));
		builder.append("Serial number: " + common.getSerialNumber()
				+ System.getProperty("line.separator"));
		builder.append("GPS latitude: " + gpsService.getLatitude()
				+ System.getProperty("line.separator"));
		builder.append("GPS longitude: " + gpsService.getLongitude()
				+ System.getProperty("line.separator"));
		builder.append("GPS time: " + gpsService.getTime()
				+ System.getProperty("line.separator"));
		builder.append("GPS accuracy: " + gpsService.getAccuracy() + " / "
				+ common.getGPSMinAccuracy() + System.getProperty("line.separator"));
		builder.append("GPS altitude: " + gpsService.getAltitude()
				+ System.getProperty("line.separator"));
		builder.append("GPS speed: " + gpsService.getSpeed()
				+ System.getProperty("line.separator"));
		builder.append("GPS provider: " + gpsService.getProvider()
				+ System.getProperty("line.separator")
				+ System.getProperty("line.separator"));

		if (fragmentSummary != null && fragmentSummary.isAdded()) {
			TextView summaryText = (TextView) findViewById(R.id.textview_main_summary);
			summaryText.setText(builder);
		}
	}

	private void sendSOS() {

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		String latitude = prefs.getString(
				getString(R.string.key_last_known_gps_lat),
				getString(R.string.default_last_known_gps_lat));
		String longitude = prefs.getString(
				getString(R.string.key_last_known_gps_lon),
				getString(R.string.default_last_known_gps_lon));
		Long time = Long.parseLong(prefs.getString(
				getString(R.string.key_last_known_gps_time),
				getString(R.string.default_last_known_gps_time)));
		String gpsData = latitude + ',' + longitude;
		String key = getString(R.string.key_notification_message);
		String defaultKey = getString(R.string.default_notification_message);
		DataFromDevice dataFromDevice = new DataFromDevice(common.getDeviceType(),
				common.getSenderID(), common.getSerialNumber(), gpsData, time,
				Common.COMMAND_SOS, common.getSharedPreferenceByKey(key,
						defaultKey));

		starCommService(dataFromDevice, getString(R.string.message_sending_sos));

		startLocinfoService();
	}

	private void getDeviceLocations() {
		String gpsData = "None";
		Long timeStamp = (long) 0;
		DataFromDevice dataFromDevice = new DataFromDevice(common.getDeviceType(),
				common.getSenderID(), common.getSerialNumber(), gpsData, timeStamp,
				Common.COMMAND_GETALLDEVICES);

		starCommService(dataFromDevice,
				getString(R.string.message_get_device_locations));
	}

	public void sendModeToServer(String item) {
		common.updateSharedPreferenceByKey(
				getString(R.string.key_operation_mode), item);
		common.setOperationMode(item);
		refreshSummaryText();

		String gpsData = "None";
		Long timeStamp = (long) 0;
		DataFromDevice dataFromDevice = new DataFromDevice(common.getDeviceType(),
				common.getSenderID(), common.getSerialNumber(), gpsData, timeStamp,
				Common.COMMAND_CHANGEARDUINOMODE);

		starCommService(dataFromDevice,
				getString(R.string.message_change_arduino_mode));
	}

	public void changeMode() {
		AlertDialog.Builder alertMode = new AlertDialog.Builder(
				MainActivity.this);
		alertMode.setTitle(getString(R.string.menu_title_mode));
		final String[] items = getResources().getStringArray(
				R.array.modeListOptions);
		alertMode.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String item = getResources().getStringArray(
						R.array.modeListValues)[which];

				sendModeToServer(item);
			}
		});
		alertMode.show();
	}
	
	private void getCarList() {
		String gpsData = "None";
		Long timeStamp = (long) 0;
		DataFromDevice dataFromDevice = new DataFromDevice(common.getDeviceType(),
				common.getSenderID(), common.getSerialNumber(), gpsData, timeStamp,
				Common.COMMAND_GETCARLIST);

		starCommService(dataFromDevice,
				getString(R.string.message_get_car_list));
	}

	private void chooseCar() {
		AlertDialog.Builder alertMode = new AlertDialog.Builder(
				MainActivity.this);
		alertMode.setTitle(getString(R.string.menu_title_choose_car));

		final CharSequence[] cars = common.loadCarList();

		if (cars != null) {
			alertMode.setItems(cars, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					common.updateSharedPreferenceByKey(
							getString(R.string.key_current_car_key),
							common.carList.get(which).getCarKey());
					common.updateSharedPreferenceByKey(
							getString(R.string.key_current_car_name),
							common.carList.get(which).getCarName());
					common.setCurrentCarName(common.carList.get(which)
							.getCarName());
					refreshSummaryText();
				}
			});
			alertMode.show();
		} else {
			common.displayToast(getString(R.string.message_no_car));
		}
	}

	private BroadcastReceiver commServiceDone = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			setProgressBarIndeterminateVisibility(false);
			// unregisterReceiver(commServiceDone);
			// unregisterReceiver(commServiceReceiver);
		}
	};
	
	private BroadcastReceiver commServiceError = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			setProgressBarIndeterminateVisibility(false);
			common.displayToast("Commservice error");
		}
	};

	@Override
	public void buttonClicked(int buttonID) {
		vibrator.vibrate(vibrationLength);

		switch (buttonID) {
		case R.id.imageArduino:
			Intent sensorsIntent = new Intent(MainActivity.this, Get_SensorData.class);
			startActivity(sensorsIntent);
			break;
		case R.id.imageChooseCar:
			chooseCar();
			break;
		case R.id.imageGPS:
			Intent gpsIntent = new Intent(MainActivity.this, GPSActivity.class);
			startActivity(gpsIntent);
			break;
		case R.id.imageLock:
			Log.d(TAG, "ard.bt.connected: " + Boolean.toString(arduinoBluetoothConnected));
			if (bluetoothConnect(Common.ARDUINO_BLUETOOTH_MAC)) {				
				try {					
					byte[] bluetoothCommand = Common.COMMAND_BLUETOOTH_LOCK.getBytes("UTF-8");					
					mBluetoothSocket.getOutputStream().write(bluetoothCommand);
					Log.d(TAG, "sending 0 via bluetooth");
					common.displayToast(getString(R.string.message_lock_door));
				} catch (IOException ex) {
					Log.d(TAG, getString(R.string.message_bluetooth_communication_error));
					common.displayToast(getString(R.string.message_bluetooth_communication_error));					
				}
			}
			break;
		case R.id.imageUnlock:
			Log.d(TAG, "ard.bt.connected: " + Boolean.toString(arduinoBluetoothConnected));
			if (bluetoothConnect(Common.ARDUINO_BLUETOOTH_MAC)) {				
				try {					
					byte[] bluetoothCommand = Common.COMMAND_BLUETOOTH_UNLOCK.getBytes("UTF-8");
					mBluetoothSocket.getOutputStream().write(bluetoothCommand);
					Log.d(TAG, "sending 1 via bluetooth");
					common.displayToast(getString(R.string.message_unlock_door));
				} catch (IOException ex) {
					Log.d(TAG, getString(R.string.message_bluetooth_communication_error));
					common.displayToast(getString(R.string.message_bluetooth_communication_error));					
				}
			}			
			break;
		case R.id.imageMap:
			getDeviceLocations();
			break;
		case R.id.imageOperationMode:
			changeMode();
			break;
		case R.id.imageParking:
			parkingCar();
			break;
		case R.id.imageSos:
			sendSOS();
			break;
		default:
			break;
		}
	}
	
	@SuppressLint("NewApi")
	private void bluetoothCloseConnection() {
		arduinoBluetoothConnected = false;
		if (mBluetoothSocket.isConnected()) {
			try {
				Log.d(TAG, getString(R.string.message_bluetooth_close_communication));				
				mBluetoothSocket.close();
			} catch (IOException ex) {
			Log.d(TAG, getString(R.string.message_bluetooth_close_communication_error));
				common.displayToast(getString(R.string.message_bluetooth_close_communication_error));
			}	
		}
	}
	
	
	private boolean bluetoothConnect(String arduinoBtAddress) {
		if (arduinoBluetoothConnected) {
			return true;
		}
				
		if (mBluetoothSocket != null) {
			bluetoothCloseConnection();		
		}
		mBluetoothAdapter.cancelDiscovery();
		arduinoBluetooth = mBluetoothAdapter.getRemoteDevice(arduinoBtAddress);
		
		try {
			mBluetoothSocket = arduinoBluetooth.createRfcommSocketToServiceRecord(UUID.fromString(Common.ARDUINO_BLUETOOTH_UUID));			
			mBluetoothSocket.connect();
			return true;
		} catch (IOException ex) {				
			Log.d(TAG, getString(R.string.message_bluetooth_not_found));
			common.displayToast(getString(R.string.message_bluetooth_not_found));
			return false;
		}				
	}
		
	@SuppressWarnings("deprecation")
	private void parkingCar() {
		showParkingMap = true;
		mPageAdapter.notifyDataSetChanged();
		mPager.setCurrentItem(0);

		ImageView staticMap = (ImageView) findViewById(R.id.imageParkingMap);
		staticMap.setImageResource(R.drawable.arduino);

		String[] coordinates = common.getSharedPreferenceByKey(
				getString(R.string.key_parking_coordinates),
				getString(R.string.default_parking_coordinates)).split(",");
		Double carLatitude = Double.parseDouble(coordinates[0]);
		Double carLongitude = Double.parseDouble(coordinates[1]);

		Double ownLatitude = Double.parseDouble(common.getLastKnownLatitude());
		Double ownLongitude = Double
				.parseDouble(common.getLastKnownLongitude());

		URL mapLink = null;
		Bitmap picture = null;

		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();

		try {
			mapLink = new URL("http://maps.googleapis.com/maps/api/staticmap?"
					+ "size=" + width + "x" + height
					+ "&maptype=roadmap&scale=2"
					+ "&markers=color:red%7Clabel:C%7C" + carLatitude + ","
					+ carLongitude + "&markers=color:blue%7Clabel:A%7C"
					+ ownLatitude + "," + ownLongitude + "&sensor=false");
			/*
			 * mapLink = new
			 * URL("http://maps.googleapis.com/maps/api/staticmap?" + "size=" +
			 * width + "x" + height + "&maptype=roadmap&scale=2" +
			 * "&markers=icon:" + BitmapFactory.decodeResource(getResources(),
			 * R.drawable.marker_car) + "|" + carLatitude + "," + carLongitude +
			 * "&markers=icon:" + BitmapFactory.decodeResource(getResources(),
			 * R.drawable.marker_phone) + "|" + +ownLatitude + "," +
			 * ownLongitude + "&sensor=false");
			 */
			picture = BitmapFactory.decodeStream(mapLink.openConnection()
					.getInputStream());
		} catch (Exception ex) {
			common.displayToast("MainActivity / parkingCar: " + ex.toString());
		}

		if (fragmentParking != null && fragmentParking.isAdded()) {
			staticMap.setImageBitmap(picture);
		}
	}

	private void uploadSavedLocations() {
		try {
			if (common.isUnuploadedData()) {
				common.setSynchronizeGPS(true);

				String gpsData = common.getLastKnownLatitude() + ','
						+ common.getLastKnownLongitude();
				Long timeStamp = Long.parseLong(common.getLastKnownTime());
				DataFromDevice dataFromDevice = new DataFromDevice(
						common.getDeviceType(), common.getSenderID(),
						common.getSerialNumber(), gpsData, timeStamp,
						Common.COMMAND_STORE_GPS_DATA);

				starCommService(dataFromDevice,
						getString(R.string.message_sync_gps));
			} else {
				common.displayToast(getString(R.string.message_sync_no_data_to_upload));
			}
		} catch (Exception ex) {
			common.displayToast("MainActivity / uploadSavedLocations: "
					+ ex.toString());
		}
	}

	private void starCommService(DataFromDevice dataFromDevice,
			String startingMessage) {
		setProgressBarIndeterminateVisibility(true);
		commServiceIntent.putExtra("dataFromDevice", dataFromDevice);
		commServiceIntent.putExtra("startingMessage", startingMessage);

		// registerReceiver(commServiceReceiver, commServIntentFilter);
		// registerReceiver(commServiceDone, commServIntentFilter);
		startService(commServiceIntent);
	}
}
